package com.xiangyueEducation.uploaderCloud.service.impl;


import com.xiangyueEducation.uploaderCloud.utils.*;
import com.xiangyueEducation.uploaderCloud.utils.enums.PathEnum;
import com.xiangyueEducation.uploaderCloud.utils.*;
import com.xiangyueEducation.uploaderCloud.utils.enums.PathEnum;
import com.xiangyueEducation.uploaderCloud.utils.enums.ResultCodeEnum;
import com.xiangyueEducation.uploaderCloud.mapper.UserMapper;
import com.xiangyueEducation.uploaderCloud.mapper.mapperUtil.UserMapperUtil;
import com.xiangyueEducation.uploaderCloud.pojo.entity.User;
import com.xiangyueEducation.uploaderCloud.service.EmailService;
import com.xiangyueEducation.uploaderCloud.service.LoginService;
import com.xiangyueEducation.uploaderCloud.utils.enums.ResultCodeEnum;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class LoginServiceImpl implements LoginService  {

    @Autowired
    private EmailService emailService;

    @Resource
    private UserMapper userMapper;

    @Autowired
    private UserMapperUtil userDTO;
    @Autowired
    private JwtHelper jwtHelper;
    @Autowired
    CaptchaUtil captchaUtil;

    @Override
    public Result<?> login(User user) {
        //检查用户名是否存在
        User dbUser = userDTO.selectByUsername(user.getNumber());
        if (dbUser == null) return Result.build("用户名或密码错误", ResultCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        //检查密码是否正确
        boolean res =checkPwd(user,dbUser) ;
        //成功则返回token以及200
        if (res){
            //生成token
            return Result.ok(jwtHelper.createToken(dbUser.getId()));
        }
        return Result.build("用户名或密码错误", ResultCodeEnum.USERNAME_OR_PASSWORD_ERROR);
    }

    @Override
    public Result<?> checkUsernameUsed(String username) {
        return userDTO.selectByUsername(username)!=null?Result.build("用户名已被使用",ResultCodeEnum.USERNAME_USED):Result.ok("用户名未被使用");
    }

    @Override
    public Result<?> register(User registerInfo,String captcha) {
        if (!captchaUtil.verifyCaptcha(registerInfo.getNumber(), captcha)) return Result.build("验证码错误", ResultCodeEnum.CAPTCHA_ERROR);
        //检查用户名
        Result<?> result = checkUsernameUsed(registerInfo.getNumber());
        if (result.getCode().equals(ResultCodeEnum.USERNAME_USED.getCode())) return result;
        //添加默认头像
        registerInfo.setAvatar("classpath:"+PathEnum.DEFAULT_AVATAR.getPath());
        //加密密码并注册
        String encrypt = EncryptUtil.encrypt(registerInfo.getPwd());
        registerInfo.setPwd(encrypt);
        userMapper.insert(registerInfo);
        return Result.ok("注册成功");

    }

    @Override
    public Result<?> add(User registerInfo) {
        registerInfo.setRoleId(1);
        //检查用户名
        Result<?> result = checkUsernameUsed(registerInfo.getNumber());
        if (result.getCode().equals(ResultCodeEnum.USERNAME_USED.getCode())) return result;
        //添加默认头像
        registerInfo.setAvatar("classpath:"+PathEnum.DEFAULT_AVATAR.getPath());
        //加密密码并注册
        String encrypt = EncryptUtil.encrypt(registerInfo.getPwd());
        registerInfo.setPwd(encrypt);
        userMapper.insert(registerInfo);
        return Result.ok("注册成功");
    }

    @Override
    public Result<?> checkLogin(String token) {
        return jwtHelper.isExpiration(token)?Result.build("登录已过期",ResultCodeEnum.NOT_LOGIN):Result.ok("登录未过期");
    }

    @Override
    public Result<?> changePwd(HashMap<String, String> pwdInfo, String token) {
        String originalPwd = pwdInfo.get("originalPwd");
        User dbUser = userMapper.selectById(jwtHelper.getUserId(token));

        User user = new User();
        user.setPwd(originalPwd);
        if(checkPwd(user,dbUser)){
            //配置新密码和salt
            dbUser.setPwd(EncryptUtil.encrypt(pwdInfo.get("newPwd")));
            //插入
            userMapper.updateById(dbUser);
            return Result.ok("密码修改成功");
        }
        return Result.build("密码错误",ResultCodeEnum.PASSWORD_ERROR);
    }

    @Override
    public Result<?> getCaptcha(String username,String email) {
        //如果已经获取过了, 那么返回一个700错误
        if (captchaUtil.isCaptchaValid(username)) return Result.build("不要重复获取验证码", ResultCodeEnum.CAPTCHA_REQUEST_REPEAT);
        //否则
        //生成验证码
        String captcha = captchaUtil.generateCaptcha(username);
        //邮箱发送验证码
        emailService.sendCaptcha(email,captcha);
        //返回成功操作信息
        return Result.ok("验证码获取成功, 请您前往邮箱查看");

    }

    @Override
    public Result<?> verifyCaptcha(String username,String captcha) {
        //验证是否过期
        if (!captchaUtil.isCaptchaValid(username)) return Result.build("验证码已过期",ResultCodeEnum.CAPTCHA_EXPIRED);
        //是否正确
        return Result.ok(captchaUtil.verifyCaptcha(username,captcha)?"验证码正确":"验证码错误请重试");
    }


    private boolean checkPwd(User user, User dbUser) {
        String encrypt = EncryptUtil.encrypt(user.getPwd());
        System.out.println("encrypt = " + encrypt);
        return encrypt.equals(dbUser.getPwd());
    }



}
